import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/bottom_sheet/bottom_sheet_select.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class ExpirationReminder extends StatefulWidget {
  const ExpirationReminder({Key? key}) : super(key: key);

  @override
  State<ExpirationReminder> createState() => _ExpirationReminderState();
}

class _ExpirationReminderState extends State<ExpirationReminder> {
  // 租期到期提醒时间（天）
  int _leaseExpirationReminderDays = 7;
  // 账单到期提醒时间（天）
  int _billExpirationReminderDays = 3;
  // 公寓信息
  Map _apartmentInfo = {};
  
  // 生成1-30天的选项列表
  List<int> _getDaysList() {
    return List.generate(30, (index) => index + 1);
  }
  
  // 弹出底部选择框
  void _showDaysSelector(bool isLease) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return BottomSheetSelect(
          items: _getDaysList(),
          itemAsString: (item) => "$item 天",
          compare: (item) => isLease ? item == _leaseExpirationReminderDays : item == _billExpirationReminderDays,
        );
      }
    ).then((value) {
      if (value != null) {
        setState(() {
          if (isLease) {
            _leaseExpirationReminderDays = value;
          } else {
            _billExpirationReminderDays = value;
          }
        });
      }
    });
  }

  // 获取公寓信息
  void _getApartmentInfo() async {
    EasyLoading.show();
    Map res = await apartmentApi.getApartmentInfo();
    EasyLoading.dismiss();
    setState(() {
      _apartmentInfo = res["data"] ?? {};
      _leaseExpirationReminderDays = _apartmentInfo["leaseExpirationReminderDays"] ?? 7;
      _billExpirationReminderDays = _apartmentInfo["billExpirationReminderDays"] ?? 3;
    });
  } 
  
  // 保存设置
  void _saveSettings() async{
    // 保存设置
    EasyLoading.show(status: "保存中...");
    apartmentApi.updateApartmentInfo({
      "apartmentId": _apartmentInfo["apartmentId"],
      "leaseExpirationReminderDays": _leaseExpirationReminderDays,
      "billExpirationReminderDays": _billExpirationReminderDays,
    });
    EasyLoading.showSuccess("保存成功");
    await Future.delayed(const Duration(seconds: 2));
    _getApartmentInfo();
  }

  @override
  void initState() {
    super.initState();
    _getApartmentInfo();
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "即将到期设置",
      child: Padding(
        padding: EdgeInsets.all(ThemeVars.paddingPage),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            MenuBlock(
              items: [
                MenuBlockItem(
                  text: "租期即将到期提醒时间",
                  suffix: Text("$_leaseExpirationReminderDays 天"),
                  onTap: () {
                    _showDaysSelector(true);
                  }
                ),
                MenuBlockItem(
                  text: "账单即将到期提醒时间",
                  suffix: Text("$_billExpirationReminderDays 天"),
                  onTap: () {
                    _showDaysSelector(false);
                  }
                ),
              ],
            ),
            SizedBox(height: 30),
            Button(
              type: ButtonType.primary,
              onPressed: _saveSettings,
              child: const Text("保存")
            ),
          ],
        ),
      )
    );
  }
}
